package com.lg.startertemplate.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.lg.startertemplate.config.DataSourceManager;
import com.lg.startertemplate.domain.jdbc.DataSourceConfig;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@RestController
@Api(tags = "数据源动态操作")
public class DataSourceController {

    @Autowired
    public DataSourceManager dataSourceManager;

    /**
     *  初始给一个
     *  此处为测试方法
     */
    @PostConstruct
    public DruidDataSource initDatasource(){
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setName("defaultDatasource");

        dataSourceConfig.setDriver("org.postgresql.Driver");
        dataSourceConfig.setUrl("jdbc:postgresql://192.168.120.85:5431/gang");
        dataSourceConfig.setPassword("postgres");
        dataSourceConfig.setUser("postgres");

        return dataSourceManager.createDatasource(dataSourceConfig);
    }


    @GetMapping("createDatasource")
    public String createDatasource(String name){
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setName(name);

        dataSourceConfig.setDriver("org.postgresql.Driver");
        dataSourceConfig.setUrl("jdbc:postgresql://192.168.120.85:5431/gang1");
        dataSourceConfig.setPassword("postgres");
        dataSourceConfig.setUser("postgres");

        dataSourceManager.createDatasource(dataSourceConfig);
        return dataSourceConfig.getName();
    }

    @GetMapping("getDatasource")
    public String getDatasource(String name){
        DruidDataSource datasource = dataSourceManager.getDatasource(name);
        return "suss";
    }

}
